package com.bye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bye.dto.ManagerDto;
import com.bye.dto.MenuDto;
import com.bye.exception.MyException;
import com.bye.mapper.ManagerMapper;
import com.bye.mapper.MenuMapper;
import com.bye.service.ManagerService;
import com.bye.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private JwtUtils jwtUtils;


    //登录
    @Override
    public String login(ManagerDto managerDto) throws MyException {
        QueryWrapper qr = new QueryWrapper();
        Map map = new HashMap();
        map.put("account_manager",managerDto.getAccountManager());
        map.put("password_manager",managerDto.getPasswordManager());
        qr.allEq(map);
        ManagerDto managerDto1 = managerMapper.selectOne(qr);
        //判断查询结果是否为空
        if (managerDto1 != null) {
            //不为空, 则登录成功
            return jwtUtils.generateToken(managerDto1.getAccountManager());
        }
        //登录失败
        throw  new  MyException("登录失败, 请检查账号密码!");
    }

    //根据账号获取登录信息
    public ManagerDto getManagerDtoByAccountManager(String accountManager) {
        QueryWrapper qr = new QueryWrapper();
        qr.eq("account_manager",accountManager);
        ManagerDto managerDto = managerMapper.selectOne(qr);
        return managerDto;
    }

    public List<MenuDto> selectMenuById(Integer managerId) throws MyException{
        List<Integer> roleList = managerMapper.selectRoleByUserId(managerId);
        System.out.println("改用户拥有的权限"+roleList);
        if (roleList == null || roleList.size() == 0){
            throw new MyException("用户未配置任何角色");
        }

        //        根据用户所有的权限查看菜单
        List<MenuDto> menuDtoList = menuMapper.selectMenuByRole(roleList);
        if (menuDtoList == null || menuDtoList.size() == 0){
            throw new MyException("用户未配置任何角色");
        }
        return menuDtoList;
    }

}
